package com.ken.ability.gateway.auth.exception;

import com.alibaba.fastjson.JSON;
import com.ken.entity.base.protocol.R;
import com.ken.entity.base.util.RCode;
import com.ken.entity.base.util.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 异常处理器
 */
@Slf4j
@Component
public class AuthExceptionHandler implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
        log.error("[gateway-auth-error] 网关认证失败!!");

        ServerHttpResponse response = serverWebExchange.getResponse();
        //设置相应时间
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //设置返回类型
        response.getHeaders().add("Content-Type", "application/json;character=utf-8;");
        //设置内容

        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            //创建返回的对象
            R<Object> r = ResultUtils.createFail(RCode.AUTH_INVALID);
            return dataBufferFactory.wrap(JSON.toJSONString(r).getBytes());
        }));
    }
}
